package com.bydq.patrolsystem.interceptor;

import com.bydq.patrolsystem.entity.PsUser;
import com.bydq.patrolsystem.mapper.PsRolePremissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 权限鉴别拦截器
 */
@Component
public class AuthorityInterceptor implements HandlerInterceptor {

    @Autowired
    private PsRolePremissionMapper psRolePremissionMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前用户
        HttpSession session = request.getSession();
        PsUser user = (PsUser) session.getAttribute("user");
        //如果为空说明没登录 让他先登录
        if (user == null)
            return true;

        String url = request.getServletPath();

        //获得当前角色的权限url集合
        List<String> urls = psRolePremissionMapper.selectFunctionUrlByRoleId(user.getRoleId());

        //当前访问的url 中包含 角色可以访问的url 也可以访问 防止rest风失效
        if(urls!=null) {
            for (String s : urls) {
                if (url.contains(s))
                    return true;
            }
        }

        //没有就去到待办页面
        response.sendRedirect("/agenda?flag=-1");
        return false;
    }
}
